#coding:utf-8

import time
import MySQLdb
from flask import Flask,g,request,make_response,redirect,url_for,render_template
from tools import *
import hashlib
import xml.etree.ElementTree as ET
import json
import urllib
import urllib2
import pylibmc
import os

app = Flask(__name__)

app.debug=True

from sae.const import (MYSQL_HOST, MYSQL_HOST_S,
    MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
)

@app.before_request
def before_request():
    g.db = MySQLdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS,
                           MYSQL_DB, port=int(MYSQL_PORT))

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'): g.db.close()
        
        
@app.route('/test',methods=['GET','POST'])
def h_getdata():
    return "1,0,1,0,2,0"

@app.route('/demo', methods=['GET', 'POST'])
def greeting():
    html = ""

    if request.method == 'POST':
        c = g.db.cursor()
        c.execute("insert into info (NAME) values(%s)", (request.form['text'].encode("utf-8").strip()))

    html += """
    <form action="" method="post">
        <div><textarea cols="40" name="text"></textarea></div>
        <div><input type="submit" /></div>
    </form>
    """
    c = g.db.cursor()
    c.execute('select * from info')
    msgs = list(c.fetchall())
    msgs.reverse()
    for row in msgs:
        html +=  '<p>NAME:' + row[-1] + '</p>'

    return html

@app.route("/qzone")
def qzone():
    from autoqzone import *
    qz=qzone('AR6u0DtvxgISDPx231cftvYf')
    dic,dic2={},{}
    passive()
    return "ok"

@app.route("/bing_qiniu")
def bing_qiniiu():
    from bingtu import *
    b = BingPic()
    c = b.getBingImageUrl(b.readCNBingPage())
    from qiniucunchu import qiniufetch
    qiniufetch(c,"music",str(int(time.time()))+".jpg")
    return "OK"

@app.route('/')
def root():
    #app_root = os.path.dirname(__file__)
    #staticPath = os.path.join(app_root, 'static')
    #return u"主页正在开发中，敬请期待"
    #return staticPath
    #return staticPath+'/wuziqi/index.html'
    #return render_template("index.html")
	return redirect(url_for('static', filename='wuziqi/index.html'), code=301)
	return app.send_static_file(os.path.join(app.root_path, 'static/wuziqi/index.html'))
@app.route('/weixin',methods=['GET','POST'])
def wechat_auth():
	if request  .method == 'GET':
		token='test'
		data = request.args
		signature = data.get('signature','')
		timestamp = data.get('timestamp','')
		nonce = data.get('nonce','')
		echostr = data.get('echostr','')
		s = [timestamp,nonce,token]
		s.sort()
		s = ''.join(s)
		if (hashlib.sha1(s).hexdigest() == signature):
			return make_response(echostr)
	else:    
		rec = request.stream.read()
		xml_rec = ET.fromstring(rec)
		tou = xml_rec.find('ToUserName').text
		fromu = xml_rec.find('FromUserName').text
		mstype = xml_rec.find("MsgType").text
		if mstype == "event":
			content = xml_rec.find("Event").text
			if content == "subscribe":
				replay = u"""
你好，这里是SmartHouse项目小组微信服务

1、直接回复实现中英文翻译
2、关键字“每日美女”：图片一枚
3、关键字“每日诗词”:诗或词或文章一篇
4、关键字“每日音乐”：精选音乐一首【尽量在WIFI环境下使用】
5、如需帮助及其他功能，请点击相应按钮

恩，忘了，多谢关注！

—— SmartHouse项目小组
"""
				return responseText(replay)

			if content == "unsubscribe":
				replay = u'我现在功能还很简单，知道满足不了您的需求，但是我会慢慢改进，欢迎您以后再来'
				return responseText(replay)
		if mstype == 'text':
			content = xml_rec.find('Content').text
			if type(content).__name__ == "unicode":
				content = content.encode("UTF-8")
			#print "test"
            #关键字
			if content == '每日音乐':
				return responseText(fromu,tou,u"正在搜索音乐资源，稍等时日为您提供音乐服务。")
				
			if content == '每日美女':
				return responseText(fromu,tou,u"正在搜索美，，，，哎呀，老婆不让传呀。")
                #return r = responseText(fromu,tou,u"正在搜索音乐资源，稍等时日为您提供音乐服务。")
				
			if content == '每日诗词':
				return responseText(fromu,tou,u"正在搜索诗词资源，稍等时日为您提供相应服务。")
			if content =='帮助':
				replay = u"""
你好，这里是SmartHouse项目小组微信服务

1、直接回复实现中英文翻译
2、关键字“每日美女”：图片一枚
3、关键字“每日诗词”:诗或词或文章一篇
4、关键字“每日音乐”：精选音乐一首【尽量在WIFI环境下使用】
5、如需帮助及其他功能，请点击相应按钮

—— SmartHouse项目小组敬上"""
				return responseText(fromu,tou,replay)
                
				
            
            
            
            
            ##百度翻译
                
			replay = translate(content)         
			return responseText(fromu,tou,replay)

@app.route("/weixin/bingtu")
def bing():
    from bingtu import *
    b = BingPic()
    c = b.getBingImageUrl(b.readCNBingPage())
    #from qiniucunchu import qiniufetch
    #qiniufetch(c,"music","111.jpg")
    return r"""<!DOCTYPE html>
			<html>
			<body>

			<h2></h2>
			<img border="0" src="""+c+r""" alt="小斋吟玩" width=100% height=90%>

			</body>
			</html>		 """ 
        

        
def responseText(fromu,tou,text):
    xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
    response = make_response(xml_rep % (fromu,tou,str(int(time.time())),text))
    response.content_type='application/xml'
    return response

def responseMusic(fromu,tou,music):
    xml_music = "<ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[music]]></MsgType><Music><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><MusicUrl><![CDATA[%s]]></MusicUrl><HQMusicUrl><![CDATA[%s]]></HQMusicUrl></Music><FuncFlag>0</FuncFlag></xml>"
    response = make_response(xml_music % (fromu,tou,str(int(time.time())),music))
    response.content_type='application/xml'
    return response

#def responsePicture(fromu,tou,music):